package com.example.banner.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.banner.service.OssService;
import com.example.banner.util.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFile(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String keyid = ConstantPropertiesUtils.KEY_ID;
        String keysecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketname = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            OSS oss = new OSSClientBuilder().build(endpoint, keyid, keysecret);
            InputStream inputStream = file.getInputStream();
            //获得上传的文件名称
            String fileName = file.getOriginalFilename();
            //上传到OSS
            oss.putObject(bucketname, fileName, inputStream);
            oss.shutdown();
            //返回给前端的URL地址
            String url = "https://" + bucketname + "." + endpoint + "/" + fileName;
            return url;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
